<template>
    <div class="app-container">
        <!-- 搜索栏 -->
        <el-form ref="queryRef" :inline="true" label-width="68px" :model="queryParams" v-show="showSearch">
            <el-form-item label="分类">
                <el-cascader v-model="queryCategoryIdList" :props="categoryProps" @change="handleCategoryChange"
                    style="width: 100%;" />
            </el-form-item>
            <el-form-item label="品牌">
                <el-select class="m-2" placeholder="选择品牌"  style="width: 100%"
                    v-model="queryParams.brandId">
                    <el-option v-for="item in brandList" :key="item.id" :label="item.name" :value="item.id" />
                </el-select>
            </el-form-item>
            <el-form-item>
                <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
                <el-button icon="Refresh" id="reset-all" @click="resetQuery">重置</el-button>
            </el-form-item>
        </el-form>
        <!-- 功能按钮 -->
        <el-row :gutter="10" class="mb8">
            <el-col :span="1.5">
                <el-button type="primary" plain icon="Plus" @click="handleAdd()">
                    新增
                </el-button>
                <el-button type="success" plain icon="Edit" :disabled="single"
                    @click="handleUpdate(batchData.data[0].id)">
                    修改
                </el-button>
                <el-button type="danger" plain icon="Delete" :disabled="multiple" @click="handleBatchDelete(batchData)">
                    删除
                </el-button>
            </el-col>
            <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
        </el-row>
        <!-- 数据展示表格 -->
        <el-table :data="categoryBrandList" v-loading="loading" @selection-change="handleSelectionChange">
            <el-table-column type="selection" width="55" align="center" />
            <el-table-column label="分类名称" prop="categoryName" />
            <el-table-column label="品牌名称" prop="brandName" />
            <el-table-column label="品牌图标" prop="logo" #default="scope">
                <img :src="scope.row.logo" alt="" style="width: 50px" />
            </el-table-column>
            <el-table-column label="创建时间" prop="createTime" />
            <el-table-column label="操作" align="center" class-name="small-padding fixed-width" #default="scope">
                <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row.id)">修改</el-button>
                <el-button link type="primary" icon="Delete"
                    @click="handleDelete(scope.row.id, scope.row.categoryName, scope.row.brandName)">删除</el-button>
            </el-table-column>
        </el-table>
        <!-- 添加和修改分类品牌 对话框 -->
        <el-dialog :title="title" v-model="open" :rules="rules" width="500px" append-to-body>
            <el-form ref="categoryBrandRef" :model="form" label-width="80px">
                <el-form-item label="分类" prop="categoryIdList">
                    <el-cascader :props="categoryProps" v-model="form.categoryIdList" />
                </el-form-item>
                <el-form-item label="品牌" prop="brandId">
                    <el-select v-model="form.brandId" class="m-2" placeholder="选择品牌" style="small">
                        <el-option v-for="item in brandList" :key="item.id" :label="item.name" :value="item.id" />
                    </el-select>
                </el-form-item>
            </el-form>
            <template #footer>
                <div class="dialog-footer">
                    <el-button type="primary" @click="submitFormConfim">确 定</el-button>
                    <el-button @click="cancle">取 消</el-button>
                </div>
            </template>
        </el-dialog>
        <!-- 分页 -->
        <Pagination v-show="total > 0" layout="sizes,prev,pager,next,jumper,->,total,slot" :total="total"
            v-model:page="queryParams.pageNum" v-model:limit="queryParams.pageSize" :page-sizes="[10, 20, 50, 100]"
            @pagination="getList" />
    </div>
</template>

<script setup name="categoryBrand">
import Pagination from './../../../components/Pagination/index.vue'
import { listCategoryBrand, addCategoryBrand, getCategoryBrandDetail, updateCategoryBrand, deleteCategoryBrand } from "@/api/product/categoryBrand.js";
import { getCurrentInstance, reactive, ref } from "vue";
import { getCategoryListByParentId } from '@/api/product/category'
import { getBrandAll } from "@/api/product/brand.js";


const { proxy } = getCurrentInstance();
//搜索栏id列表
const queryCategoryIdList = ref([]);
//品牌 列表
const brandList = ref([]);
// 分类 的层叠下拉列表配置选项
const categoryProps = {
    expandTrigger: 'hover',
    lazy: true,
    value: 'id',
    label: 'name',
    lazyLoad(node, resolve) {
        if (!node.value) node.value = 0
        getCategoryListByParentId(node.value).then((response) => {
            const data = response.data;
            data.forEach(element => {
                element.leaf = !element.hasChildren
            })
            resolve(data)
        })
    }
}
//是否显示搜索栏
const showSearch = ref(true);
//数据展示表格数据
const categoryBrandList = ref([]);

const data = reactive({
    //查询参数
    queryParams: {
        pageNum: 1,
        pageSize: 10,
        categoryId: null,
        brandId: null,
    },
    //表单数据
    form: {
        id: null,
        categoryId: null,
        categoryIdList: [],
        brandId: null
    },
    //校验规则
    rules: {
        categoryIdList: [
            { required: true, message: '请选择分类', trigger: 'blur' }
        ],
        brandId: [
            { required: true, message: '请选择品牌', trigger: 'blur' }
        ]
    }
})
const { queryParams, form, rules } = toRefs(data);
const total = ref(0);
//新增修改对话框弹出控制
const open = ref(false);
//对话框标题
const title = ref();
const batchData = reactive({
    data: []
})
//单选控制
const single = ref(true);
//多选控制
const multiple = ref(true);
//加载数据时显示的动效控制
const loading = ref(true);

function getList() {
    listCategoryBrand(queryParams.value).then(res => {
        categoryBrandList.value = res.rows;
        total.value = res.total;
        loading.value = false;
    })
}
//查询全部品牌信息
function getBrandAllList() {
    getBrandAll().then(response => {
        brandList.value = response.data
    })
}
// 分类选择改变时的回调 // 获取当前选中的分类id
const handleCategoryChange = () => {
    if (queryCategoryIdList.value.length == 3) {
        queryParams.value.categoryId = queryCategoryIdList.value[2]
    }
}

//搜索操作
function handleQuery() {
    queryParams.value.pageNum = 1;
    getList();
}
//重置操作
function resetQuery() {
    queryCategoryIdList.value = [];
    proxy.resetForm("queryRef");
    queryParams.value.brandId = null;
    queryParams.value.categoryId = null;
    handleQuery();
}
//新增操作
function handleAdd() {
    open.value = true;
    title.value = "新增分类品牌";
    reset();
}
//表单重置
function reset() {
    form.value = {
        id: null,
        categoryId: null,
        categoryIdList: [],
        brandId: null
    }
    proxy.resetForm("categoryBrandRef");
}

//提交
function submitFormConfim() {
    proxy.$refs["categoryBrandRef"].validate(
        valid => {
            if (valid) {
                if (form.value.id != null) {
                    const { id, categoryIdList, brandId } = form.value;
                    const _categoryId = categoryIdList[form.value.categoryIdList.length - 1]
                    const data = {
                        id: id,
                        categoryIdList: categoryIdList,
                        categoryId: _categoryId,
                        brandId: brandId,
                    }
                    updateCategoryBrand(data).then(
                        response => {
                            open.value = false;
                            proxy.$modal.msgSuccess("修改成功");
                            reset();
                            getList();
                        }
                    ).catch(
                        error => {
                            proxy.$modal.msgError("修改失败");
                            console.log(error);
                        }
                    )
                } else {
                    const { categoryIdList, brandId } = form.value;
                    const _categoryId = categoryIdList[form.value.categoryIdList.length - 1]
                    const data = {
                        categoryId: _categoryId,
                        brandId: brandId,
                    }
                    addCategoryBrand(data).then(
                        response => {
                            open.value = false;
                            proxy.$modal.msgSuccess("新增成功");
                            reset();
                            getList();
                        }
                    ).catch(
                        error => {
                            proxy.$modal.msgError("新增失败");
                            console.log(error);
                        }
                    )
                }
            }
        }
    )
}
//取消
function cancle() {
    open.value = false;
    reset();
}
//修改
function handleUpdate(id) {
    reset();
    open.value = true;
    title.value = "修改分类品牌";
    getCategoryBrandDetail(id).then(
        response => {
            form.value.id = response.data.id;
            form.value.categoryId = response.data.categoryId;
            form.value.brandId = response.data.brandId;
            form.value.categoryIdList = response.data.categoryIdList;
        }
    )
}

//删除
function handleDelete(id, categoryName, brandName) {
    proxy.$modal.confirm('是否确认删除分类 ' + categoryName + ' 下的品牌: ' + brandName).then(
        () => {
            return deleteCategoryBrand(id);
        }
    ).then(
        () => {
            getList();
            proxy.$modal.msgSuccess("删除成功");
        }
    )
}
//批量删除
function handleBatchDelete(batchData) {
    //确认删除的数据
    var ids = [];
    const promises = batchData.data.map(item => {
        return new Promise((resolve, reject) => {
            proxy.$modal
                .confirm('是否确认删除分类 ' + item.categoryName + ' 下的品牌: ' + item.brandName)
                .then((confirmed) => {
                    confirmed ? ids.push(item.id) : null;
                    resolve();
                }).catch(() => { resolve() })
        });
    });

    Promise.all(promises).then(() => {
        if(ids.length == 0 ) {
            proxy.$modal.msg("没有选择删除任何条目");
            getList();
        }
        else{
            deleteCategoryBrand(ids).then(
                () => {
                    getList();
                    proxy.$modal.msgSuccess("删除成功");
                }
            )
        }
    })
    batchData.data = [];
}
//多选框变化时
function handleSelectionChange(selection) {
    batchData.data = [];
    selection.forEach(item => batchData.data.push({
        id: item.id,
        categoryName: item.categoryName,
        brandName: item.brandName
    }))
    //选中1条为false
    single.value = selection.length != 1;
    //没选为true
    multiple.value = !selection.length;
}

//自动调用
getBrandAllList();
getList();
</script>

<style></style>